import { Button, message, Spin } from 'antd'
import React, { Fragment, useCallback, useContext, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom';

import { reqRole, reqUpadtePassword, reqUpdateRole } from '@/api/api';
import { Context } from '@/App';
import './userinfor.less'

import UpdateInformationForm from '@/components/UserInforUI/UpdateInformationForm';
import PasswordForm from '@/components/UserInforUI/PasswordForm';
import UserInforCard from '@/components/UserInforUI/UserInforCard';
import UserInforHeade from '@/components/UserInforUI/UserInforHeade';
import NotFoundContent from '@/components/HomeUI/Content/404';

export default function UserInfor() {
  const [openInfor, setOpenInfor] = useState(false);
  const [openPassword, setPassword] = useState(false);
  const [userHeadInfor, setUserHeadInfor] = useState();
  const [userCardInfor, setUserCardInfor] = useState();
  const [updateResult, setUpdateResult] = useState(false);
  const [loading, setLoading] = useState(true)

  // 拿到全局状态
  const context = useContext(Context);
  const navigate = useNavigate()

  const { role } = context

  const fetchData = useCallback(() => {
    setLoading(true)
    if (role !== null) {
      reqRole(role).then(
        res => {
          if (res.status === 200) {
            setLoading(false)
            setUserHeadInfor({
              name: res.data[0].fd_name,
              idNum: res.data[0].fd_idNum,
              professional: res.data[0].fd_professionalName,
              birthday: res.data[0].fd_birthday,
              phone: res.data[0].fd_phone,
            });
            setUserCardInfor({
              nickname: res.data[0].fd_nickname,
              email: res.data[0].fd_email,
              motto: res.data[0].fd_motto,
              qq: res.data[0].fd_qq,
              hobby: res.data[0].fd_hobby,
              personalProfile: res.data[0].fd_personalProfile
            });
          }
        },
        rej => {
          console.log("错误处理");
        }
      );
    }
  }, [role]);

  useEffect(() => {
    fetchData()
  }, [fetchData, updateResult])


  const onCreateInfor = (values) => {
    const value = { ...values, role }
    reqUpdateRole(value).then(
      res => {
        if (res.status === 200) {
          // 这里可以设置弹出提示修改该成功
          message.success('修改成功！', 1, { className: "message" });
          setUpdateResult(!updateResult)
        }
      },
      rej => { }
    )
    // console.log('表单数据 ', values);
    setOpenInfor(false);
  };

  // 修改密码
  const onCreatePassword = (values) => {
    const value = { ...values, role }
    reqUpadtePassword(value).then(
      res => {
        if (res.status === 200) {
          message.success("修改成功")
          navigate('/login', { replace: true })
        }
      },
      rej => { }
    )
    setPassword(false);
  }

  if (role !== undefined && role?.fd_type !== "student" && role?.fd_type !== "teacher") {
    return (
      <NotFoundContent />
    )
  }

  const UpdateInformation = { ...userCardInfor, ...userHeadInfor }
  return (
    <Fragment>
      <div className='userInfor-box'>
        {
          loading ? <Spin size='large' className='loading' /> :
            <>
              <UserInforHeade userHeadInfor={userHeadInfor} />
              <div className='user-updata'>
                <Button onClick={() => { setOpenInfor(true) }}>修改信息</Button>
                <Button onClick={() => { setPassword(true) }}>账号安全</Button>
              </div>
              <UserInforCard userCardInfor={userCardInfor} />
            </>
        }
      </div>
      <UpdateInformationForm
        open={openInfor}
        onCreate={onCreateInfor}
        onCancel={() => {
          setOpenInfor(false);
        }}
        userCardInfor={UpdateInformation}
      />
      <PasswordForm
        open={openPassword}
        onCreate={onCreatePassword}
        onCancel={() => {
          setPassword(false);
        }}
        userRole={role}
      />
    </Fragment>
  )
}
